import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { RouteLocationNormalized } from 'vue-router'

export const useAppStore = defineStore('app', () => {
  // 状态
  const size = ref<'default' | 'small' | 'large'>('default')
  const theme = ref<'light' | 'dark'>('light')
  const loading = ref(false)
  const visitedViews = ref<RouteLocationNormalized[]>([])
  const cachedViews = ref<string[]>([])

  // 设置全局加载状态
  const setLoading = (value: boolean) => {
    loading.value = value
  }

  // 切换主题
  const toggleTheme = () => {
    theme.value = theme.value === 'light' ? 'dark' : 'light'
    localStorage.setItem('theme', theme.value)
    
    // 更新 HTML 的 class
    if (theme.value === 'dark') {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }

  // 设置组件大小
  const setSize = (value: 'default' | 'small' | 'large') => {
    size.value = value
    localStorage.setItem('size', value)
  }

  // 添加访问记录
  const addVisitedView = (route: RouteLocationNormalized) => {
    if (visitedViews.value.some(v => v.path === route.path)) return
    
    visitedViews.value.push(Object.assign({}, route))
    
    if (route.meta?.keepAlive) {
      const name = route.name as string
      if (!cachedViews.value.includes(name)) {
        cachedViews.value.push(name)
      }
    }
  }

  // 移除访问记录
  const removeVisitedView = (route: RouteLocationNormalized) => {
    const index = visitedViews.value.findIndex(v => v.path === route.path)
    if (index > -1) {
      visitedViews.value.splice(index, 1)
    }
    
    const name = route.name as string
    const cacheIndex = cachedViews.value.indexOf(name)
    if (cacheIndex > -1) {
      cachedViews.value.splice(cacheIndex, 1)
    }
  }

  // 加载用户设置
  const loadSettings = () => {
    // 加载主题设置
    const savedTheme = localStorage.getItem('theme') as 'light' | 'dark' | null
    if (savedTheme) {
      theme.value = savedTheme
      if (savedTheme === 'dark') {
        document.documentElement.classList.add('dark')
      }
    }

    // 加载组件大小设置
    const savedSize = localStorage.getItem('size') as 'default' | 'small' | 'large' | null
    if (savedSize) {
      size.value = savedSize
    }
  }

  return {
    size,
    theme,
    loading,
    visitedViews,
    cachedViews,
    setLoading,
    toggleTheme,
    setSize,
    addVisitedView,
    removeVisitedView,
    loadSettings
  }
}) 